import { ArticleDetailResponse, ArticleCommentResponse, AddArticleCommentResponse } from "@/types/data"
import { RootThunkAction } from "@/types/store"
import { http } from "@/utils/http"
// 导入 dayjs 相关包
import dayjs from "dayjs"
import localizedFormat from "dayjs/plugin/localizedFormat"
dayjs.extend(localizedFormat)
// 获取文章详情
export const getArticleById = (id: string): RootThunkAction => {
  return async (dispatch) => {
    const res = (await http.get(`/articles/${id}`)) as ArticleDetailResponse
    const detail = res.data
    // dispatch({
    //   type: "article/get",
    //   payload: {
    //     ...detail,
    //     // 格式化日期：
    //     pubdate: dayjs(detail.pubdate).locale("zh-cn").format("LL"),
    //   },
    // })
    dispatch({
      type: "article/get",
      payload: detail,
    })
  }
}
export const followAuthor = (id: string, isFollowed: boolean): RootThunkAction => {
  return async (dispatch) => {
    if (isFollowed) {
      // 取关
      await http.delete(`/user/followings/${id}`)
    } else {
      // 关注
      await http.post("/user/followings", {
        target: id,
      })
    }

    dispatch({
      type: "article/updateInfo",
      payload: {
        name: "is_followed",
        value: !isFollowed,
      },
    })
  }
}

// 获取更多文章评论数据 - 追加数据
export const getMoreArticleComments = (type: string, id: string, offset: string | null, actionType: "append" | "replace"): RootThunkAction => {
  return async (dispatch) => {
    const res = (await http.get("/comments", {
      params: {
        type,
        source: id,
        offset,
      },
    })) as ArticleCommentResponse

    dispatch({ type: "article/getArticleComments", payload: { ...res.data, actionType } })
  }
}

// 对文章发表评论
export const addArticleComment = (target: string, content: string): RootThunkAction => {
  return async (dispatch) => {
    const res = (await http.post("/comments", {
      target,
      content,
    })) as AddArticleCommentResponse

    dispatch({ type: "article/addComment", payload: res.data.new_obj })
  }
}
export const updateArticle = (articleId: string, likeing: boolean): RootThunkAction => {
  return async (dispatch) => {
    if (likeing) {
      // 点赞
      await http.post("article/likings", { target: articleId })
    } else {
      // 取消点赞
      await http.delete(`article/likings/${articleId}`)
    }
    dispatch({ type: "article/updateInfo", payload: { name: "attitude", value: likeing ? 1 : 0 } })
  }
}
